package net.searchdata.ref;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.junit.Test;

public class Entry25 {
	@Test
	public void test1() {
		List<Integer> list = Arrays.asList(1, 2, 3);
		Number value = reduce(list, 0, new Function<Integer>() {
			@Override
			public Integer apply(Integer o1, Integer o2) {
				return o1 + o2;
			}
		});

		assertThat(value.intValue(), is(6));
	}

	private <T> T reduce(List<T> list, T initValue, Function<T> function) {
		List<T> snapshot;
		synchronized (list) {
			snapshot = new ArrayList<T>(list);
		}

		T result = initValue;
		for (T o : snapshot) {
			result = function.apply(result, o);
		}
		return result;
	}
}